package org.tczs93.commonreadwrite.config;

import com.mysql.cj.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.AbstractDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author ：tao.li
 * @description：
 * @date ：Created in 2021/8/23 19:38
 */
public class CustomerDataSource  extends AbstractDataSource {
    protected static final Logger logger = LoggerFactory.getLogger(CustomerDataSource.class);


    private DataSource masterDataSource;
    private DataSource slave1DataSource;

    @Override
    public Connection getConnection() throws SQLException {
        String dbkey = RouteDataSource.getDbKey();
        logger.info("db key is:{}",dbkey);
        if(RouteDataSourceKeyEnum.MASTER.name().equals(dbkey)){
            return masterDataSource.getConnection();
        }else if(RouteDataSourceKeyEnum.SLAVE1.name().equals(dbkey)) {
            return slave1DataSource.getConnection();
        }else
            throw new IllegalStateException("发生了错误");
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        String dbkey = RouteDataSource.getDbKey();
        logger.info("username password db key is:{}",dbkey);
       if(RouteDataSourceKeyEnum.MASTER.name().equals(dbkey)){
            return masterDataSource.getConnection(username,password);
        }else if(RouteDataSourceKeyEnum.SLAVE1.name().equals(dbkey)) {
            return slave1DataSource.getConnection(username,password);
        }else
            throw new IllegalStateException("发生了错误");
    }

    public DataSource getMasterDataSource() {
        return masterDataSource;
    }

    public void setMasterDataSource(DataSource masterDataSource) {
        this.masterDataSource = masterDataSource;
    }

    public DataSource getSlave1DataSource() {
        return slave1DataSource;
    }

    public void setSlave1DataSource(DataSource slave1DataSource) {
        this.slave1DataSource = slave1DataSource;
    }
}
